import datetime
import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from house.models import House
from libs.qiniuyun.qiniu_storage import QINIUYUN_URL
from order.models import Order
from users.utils import LoginRequiredMixin

"""添加订单&获取订单列表"""
class AddOrdersView(LoginRequiredMixin, View):

    """添加订单"""
    def post(self, request):
        data = json.loads(request.body.decode())
        house_id = data.get('house_id') # 房屋ID
        start_date = data.get('start_date') # 开始时间
        end_date = data.get('end_date') # 结束时间
        # 判断参数是否齐全
        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': "4103",
                                 'errmsg': '缺少必传参数'})

        # start_date校验
        data_start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        data_end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        if data_end == data_start:
            return JsonResponse({'errno': "4103",
                                 'errmsg': '时间不能相同'})

        orders = Order.objects.filter(house_id=house_id)
        for order in orders:
            a = data_start.date()
            b = data_end.date()
            # print('a类型:',type(a))
            # print('a内容:',a)
            if a < order.end_date and a >= order.begin_date:
                return JsonResponse({'errno': "4202",
                                     'errmsg': '该时间段房屋已预订'})
            elif b <= order.end_date and b > order.begin_date:
                return JsonResponse({'errno': "4202",
                                     'errmsg': '该时间段房屋已预订'})
            elif a >= order.end_date and b <= order.begin_date:
                return JsonResponse({'errno': "4202",
                                     'errmsg': '该时间段房屋已预订'})

        user = request.user.id # 用户id
        days = data_end - data_start # 下单天数
        days = days.days
        house_price = House.objects.get(id=house_id).price    #　每晚价格

        # 保存订单基本信息 Order
        order = Order.objects.create(
            user_id=user,
            house_id=house_id,
            begin_date=start_date,
            end_date=end_date,
            days=days,
            house_price=house_price,
            amount=days * house_price
        )

        # 更新预订完成的该房屋的订单数
        res = Order.objects.filter(house_id=house_id).count()
        house = House.objects.get(id=house_id)
        house.order_count=res
        house.save()

        return JsonResponse({
            "data": {
                "order_id": order.id
            },
            "errno": "0",
            "errmsg": "下单成功"
        })

    """订单列表"""
    def get(self, request):
        role = request.GET.get('role')
        if role == 'custom':    # 房客
            user_id = request.user.id
            try:
                orders = Order.objects.filter(user_id=user_id)
            except Exception as e:
                return JsonResponse({'errno': "4001",
                                     'errmsg': '订单查询错误'})

            order_list = []
            for order in orders:

                order_list.append({
                    "amount": order.amount, # 总价
                    "comment": order.comment,   # 评论
                    "ctime": order.create_time.date(), # 创建时间
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": QINIUYUN_URL + str(order.house.index_image_url),
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": Order.ORDER_STATUS_ENUM[order.status],
                    "title": order.house.title
                })
            order_dir = {"orders": order_list}
            return JsonResponse({"data": order_dir,
                                 "errmsg": "OK",
                                 "errno": "0"})


        elif role == 'landlord':    # 房东
            user_id = request.user.id
            houses = House.objects.filter(user_id=user_id)
            order_list = []
            for house_id in houses:
                orders = Order.objects.filter(house_id=house_id.id)
                if orders:
                    for order in orders:
                        order_list.append({
                            "amount": order.amount,
                            "comment": order.comment,
                            "ctime": order.create_time.date(),
                            "days": order.days,
                            "end_date": order.end_date,
                            "img_url": QINIUYUN_URL + str(order.house.index_image_url),
                            "order_id": order.id,
                            "start_date": order.begin_date,
                            "status": Order.ORDER_STATUS_ENUM[order.status],
                            "title": order.house.title
                        })
                else:
                    continue
            return JsonResponse({
                "data": {"orders": order_list},
                "errmsg": "OK",
                "errno": "0"
            })

"""接单拒单"""
class UpOrdersView(LoginRequiredMixin, View):
    def put(self, request, order_id):
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        reason = json_dict.get('reason')

        if action is None:
            return JsonResponse({"errno": "4103",
                                 "errmsg": "缺少必传参数"
                                 })

        if action == 'accept':
            try:
                # 修改订单状态为待评价
                Order.objects.filter(id=order_id,
                                     status=0).update(status=3)
            except Exception as e:
                return JsonResponse({
                    "errno": "4004",
                    "errmsg": "修改订单出错"
                })
            return JsonResponse({
                "errno": "0",
                "errmsg": "操作成功"
            })

        if action == 'reject':
            try:
                # 修改订单状态为拒单
                Order.objects.filter(id=order_id,
                                     status=0).update(comment=reason,
                                                      status=6)

            except Exception as e:
                return JsonResponse({
                    "errno": "4004",
                    "errmsg": "修改订单出错"
                })
            return JsonResponse({
                "errno": "0",
                "errmsg": "操作成功"
            })

# 评价订单
class OrderCommentView(View):
    def put(self, request, order_id):
        comment = json.loads(request.body.decode()).get('comment')
        if not comment:
            return JsonResponse({
                "errno": "4002",
                "errmsg": "无数据"
            })
        try:
            Order.objects.filter(id=order_id).update(comment=comment,
                                                 status=4)
        except:
            return JsonResponse({
                "errno": "4103",
                "errmsg": "comment参数错误"
            })
        return JsonResponse({
            "errno": "0",
            "errmsg": "评论成功"
        })